<?php
/* 
* @Author: LDF QQ 47121862
* @Date:   2014-05-15 11:41:28
* @Last Modified by:   LDF QQ 47121862
* @Last Modified time: 2014-06-05 09:43:53
*/
class CategroyModel extends Model{
	public $table = 'category';
	public $validate=array(
		array('cname','nonull','栏目名称不能为空...',2,3),
		array('unit','nonull','单位不能为空...',2,3),
		array('price_ange','nonull','价格区间不能为空...',2,3),
		array('pid','checkPid','pid不能为空...',2,1)
	);
	//验证
	public function checkPid($name,$pid,$msg){
		$pid = intval($pid);
		if($pid===0) return true;
		// 根据栏目缓存判断pid
		$cateCache = cache('categoryCache');
		if(isset($cateCache[$pid])){
			return true;
		}else{
			return $msg;
		}
	}
	//添加栏目
	public function addCate(){
		if($this->create()){
			$id = $this->add();
			if($id){
				if($this->updateCache()){
					return $id;
				}else{
					$this->error = '更新缓存失败。。。';
					return false;
				}
			}else{
				$this->error = '添加失败...';
				return false;
			}
		}else{
			return false;
		}
	}
	//修改栏目
	public function editCate(){
		if($this->create()){
			$id = $this->save();
			if($id){
				if($this->updateCache()){
					return $id;
				}else{
					$this->error = '更新缓存失败。。。';
					return false;
				}
			}else{
				$this->error = '添加失败...';
				return false;
			}
		}else{
			return false;
		}
	}
	//删除栏目
	public function delCate(){
		$cid = Q('cid',0,'intval');
		if($this->where(array('pid'=>$cid))->find()){
			$this->error = '请先删除子栏目';
			return false;
		}
		if($this->del($cid)){
			if($this->updateCache()){
				return true;
			}else{
				$this->error = '更新缓存失败。。。';
				return false;
			}
		}else{
			$this->error = '删除失败...';
			return false;
		}
	}
	//更新缓存
	public function updateCache(){
		$cate = $this->order('cid ASC')->getField('cid,cname,pid,keywords,description,cate_type,unit,price_ange,gtid');
		$cate = Data::tree($cate,'cname');
		return cache('categoryCache', $cate);
	}
}
